package com.fan.txl.ui;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.base.txl.utils.RxUtils;
import com.elvishew.xlog.XLog;
import com.f2prateek.rx.preferences2.Preference;
import com.f2prateek.rx.preferences2.RxSharedPreferences;
import com.fan.txl.R;
import com.fan.txl.TxlApplication;
import com.fan.txl.data.base.Rsp;
import com.fan.txl.data.auth.Auth;
import com.fan.txl.data.auth.AuthReq;
import com.fan.txl.databinding.ActivityLoginBinding;
import com.fan.txl.mock.api.service.AuthService;
import com.fan.txl.ui.base.BaseActivity;
import com.fan.txl.utils.Constants;
import com.jakewharton.rxbinding2.view.RxView;
import com.trello.rxlifecycle2.android.ActivityEvent;
/*import com.github.phajduk.rxvalidator.RxValidationResult;
import com.github.phajduk.rxvalidator.RxValidator;

*/

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via email/password.
 */
public class LoginUI extends BaseActivity implements LoaderCallbacks<Cursor> {

    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };

    AuthReq mAuthReq=new AuthReq();
    ActivityLoginBinding mBinding;

    //micro query com.xgggh.srv.oauth2 Oauth2Srv.Token
    //'{"userName":"15108280907","password":"qw123456","grantType": "password",
    // "scope":"read","clientId":"e2b6abfc-3576-4fe7-9f69-1f647169a827","clientSecret":"e24e45c9-a7bc-4248-be78-17b32bea1544"}'

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAuthReq.setUserName("15108280907");
        mAuthReq.setPassword("qw123456");
        mAuthReq.setGrantType("password");
        mAuthReq.setScope("read,write");
        mAuthReq.setClientId("e2b6abfc-3576-4fe7-9f69-1f647169a827");
        mAuthReq.setClientSecret("e24e45c9-a7bc-4248-be78-17b32bea1544");

        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_login);
        mBinding.setAuthReq(mAuthReq);
        //setSupportActionBar(binding.appBarLayout);
        //LoginFilter

        // Set up the login form.
        populateAutoComplete();

      /*  mBinding.password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {

                    return true;
                }
                return false;
            }
        });*/



        RxView.clicks(mBinding.emailSignInButton)
                .throttleFirst(300, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        attemptLogin();
                    }
                });

        //校验
   /*     Observable<RxValidationResult> observable =
                RxValidator.createFor(mEmailView)
                        .nonEmpty()
                        .length( 5,"Min length is 5")
                        .onFocusChanged()
                        .toObservable();*/

    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mBinding.email, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mBinding.email.setError(null);
        mBinding.password.setError(null);

        // Store values at the time of the login attempt.

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(mAuthReq.getPassword()) && !isPasswordValid(mAuthReq.getPassword())) {
            mBinding.password.setError(getString(R.string.error_invalid_password));
            focusView = mBinding.password;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mAuthReq.getUserName())) {
            mBinding.email.setError(getString(R.string.error_field_required));
            focusView = mBinding.email;
            cancel = true;
        } else if (!isEmailValid(mAuthReq.getUserName())) {
            mBinding.email.setError(getString(R.string.error_invalid_email));
            focusView = mBinding.email;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            //showProgress(true);
            authService();
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        //return email.contains("@");
        return email.length()==11;
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() >= 4;
    }



    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginUI.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mBinding.email.setAdapter(adapter);
    }


    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    public void authService(){
        getAPIService()
                .getRpcService()
                .rpc(AuthService.methodToken,AuthService.service,AuthService.requestToken)

                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<String>bindUntilEvent(ActivityEvent.STOP))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        mLoading.setShowing(true);
                    }
                })
                .doOnTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        mLoading.setShowing(false);
                    }
                })
                .flatMap(new Function<String, Observable<Auth>>() {
                    @Override
                    public Observable<Auth> apply(String s) {
                        //RxBus
                        Preference<String> auth=getRxSharedPreferences().getString(Constants.authName);
                        Observable.just(s)
                                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_TRANSFORMER))
                                .subscribe(auth.asConsumer());
                        //data
                        Rsp<Auth> rsp = JSON.parseObject(s,  new TypeReference<Rsp<Auth>>() {});
                        return Observable.just(rsp.data);
                    }
                }).subscribe(new DisposableObserver<Auth>() {
                    @Override
                    public void onNext(Auth auth) {
                        openComponent(FeedsUI.class);
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
            });
               /* .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String s) {
                        Toast.makeText(LoginUI.this, ""+s, Toast.LENGTH_SHORT).show();
                        //RxBus
                       *//* Preference<String> auth=getRxSharedPreferences().getString(Constants.authName);
                        Observable.just(s)
                                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_TRANSFORMER))
                                .subscribe(auth.asConsumer());*//*
                        //openComponent(MsgsUI.class);
                        //finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });*/
    }


}

